package com.qdlc.p2p.biz.processor.task;


import java.text.MessageFormat;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.qdlc.p2p.biz.processor.event.NoticeValueEvent;
import com.qdlc.p2p.common.constant.NoticeTplNid;
import com.qdlc.p2p.common.core.queue.ITaskProcessor;
import com.qdlc.p2p.common.core.queue.TaskProcessorException;
import com.qdlc.p2p.common.util.DataUtils;
import com.qdlc.p2p.common.util.DateUtil;
import com.qdlc.p2p.common.util.StringUtil;
import com.qdlc.p2p.dal.common.NoticeTypeHelper;
import com.qdlc.p2p.dal.common.NoticeTypeHelper.NidType;
import com.qdlc.p2p.dal.dto.Notice;
import com.qdlc.p2p.dal.dto.NoticeType;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.util.SystemConfigs;

/**
 * 通过模版发送邮件
 * @author linya 2016-01-17
 */
@Service("noticeTemplateEmailTaskProcessor")
public class NoticeTemplateEmailTaskProcessor extends AbstractNoticeTemplateTaskProcessor {

	private static Logger logger = Logger.getLogger(NoticeTemplateEmailTaskProcessor.class);
	
	@Autowired
	@Qualifier("noticeEmailTaskProcessor")
	ITaskProcessor noticeEmailTaskProcessor;

	@Override
	protected void processInternal(String noticeTypeNid, Map<String, Object> sendData, User user) throws TaskProcessorException {
		
		//获取邮件类型，并判断是否可以发送
		NoticeType emailType = NoticeTypeHelper.getValue(noticeTypeNid, NidType.NOTICE_EMAIL);
		if(NoticeTplNid.NOTICE_SEND != emailType.getSend()){
        	return;
        }
		
		//获取邮件必要参数
		String mail = DataUtils.toString(sendData.get("email"));
		String title = StringUtil.fillTemplet(emailType.getTitleTemplet(), sendData);
		String content = StringUtil.fillTemplet(emailType.getTemplet(), sendData);
		
		//检测必要参数:无内容、无标题、无地址则不发生
		if(StringUtils.isEmpty(mail)){
			mail = user.getEmail();
		}
		
		if(StringUtils.isEmpty(mail) || StringUtils.isEmpty(title) || StringUtils.isEmpty(content)){
			return;
		}
		
		//构建邮件对象
        Notice email = new Notice();
        email.setNid(noticeTypeNid);
        email.setType(String.valueOf(NoticeTplNid.NOTICE_EMAIL));
        email.setSentUserId(SystemConfigs.ADMIN_ID);
        email.setReceiveUserId(user.getUserId());
        email.setTitle(title);
        email.setContent(content);
        email.setAddTime(DateUtil.getNow());
        email.setReceiveAddr(mail);

        //委托处理
        NoticeValueEvent event = new NoticeValueEvent();
        event.setNotice(email);
        noticeEmailTaskProcessor.process(event);
        
        logger.info(MessageFormat.format("++++发送给用户{0}的邮件成功!", user));
	}

}
